# -*- coding: utf-8 -*-
# 程序基本框架
from get_tid import get_tid 
import requests
import json
from bs4 import BeautifulSoup
import pytesseract
import StringIO
from PIL import Image
import urllib
import time 
# 设置文件编码为utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import warnings
warnings.filterwarnings("ignore")


def nike(registerinfo):
	# 耐克
	regUrl="https://unite.nike.com/join"
	regHead= {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36',
	          'Referer':'http://store.nike.com/cn/zh_cn/'}
	regData={
	"account":{"email": registerinfo['email'], "passwordSettings": {"password": registerinfo['password'], "passwordConfirm":registerinfo['password']}},
	"country": "CN",
	"dateOfBirth": registerinfo['birthday'],
	"firstName": addressinfo['firstname'][1],
	"gender": "male",
	"lastName": addressinfo['firstname'][0],
	"locale": "zh_CN",
	"mobileNumber": registerinfo['mobile'],
	"receiveEmail": "true",
	"registrationSiteId": "nikedotcom",
	"username": registerinfo['email'],
	"welcomeEmailTemplate": "TSD_PROF_COMM_WELCOME_V1.0"
	}
	r=requests.post(regUrl,data=json.dumps(regData),headers =regHead,verify=False)
	loginCookie=r.cookies
	print r.status_code
	if r.status_code==201:
		print "注册成功",zhuceCode_success
		yield zhuceCode_success
		# 添加收货信息
		# url='https://secure-store.nike.com/ap/services/jcartService?action=getCartSummary&rt=json'
		# upm=json.loads(requests.get(url,headers=regHead,cookies=loginCookie).text)['profileId']
		# print upm
		# if upm:
		# 	addressUrl='https://www.nike.com/profile/services/users/'+upm+'/addresses'
		# 	data={"additionalPhoneNumber":"",
		# 		  "address1":"江夏",
		# 		  "address2":"",
		# 		  "address3":"",
		# 		  "city":"绥化市",
		# 		  "country":"CN",
		# 		  "firstName":"胜",
		# 		  "id":'',
		# 		  "lastName":"杨",
		# 		  "otherName":'',
		# 		  "phoneNumber":"17786493932",
		# 		  "postalCode":"432000",
		# 		  "preferred":'true',
		# 		  "state":"CN-23",
		# 		  "type":"SHIPPING",
		# 		  "district":"15488",
		# 		  "countyDistrict":"安达市"}
		# 	address=requests.post(addressUrl,data=json.dumps(data),headers=regHead,cookies=loginCookie)
		# 	print address.status_code
		# 	print address.text



		
	else:
	 	print "注册失败",zhuceCode_fail
	 	yield zhuceCode_fail


# def adidas(registerinfo,addressinfo):
# 	# 阿迪达斯
# 	infoHead= {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36',
#            	   'Referer':'https://www.adidas.com.cn/customer/account/create/'}
# 	regUrl="https://www.adidas.com.cn/customer/account/createpost/"
# 	cookie=requests.get(regUrl,headers=infoHead).cookies

# 	regHead= {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36',
# 	           'Referer':'https://www.adidas.com.cn/customer/account/create/',
# 	           'cookie':str(cookie)
# 	           }

# 	infoUrl='https://www.adidas.com.cn/customer/account/create/'
# 	html=requests.get(infoUrl,headers=infoHead).text
# 	#获得token
# 	soup=BeautifulSoup(html,'html.parser')
# 	token=soup.select('input')[1]['value']
# 	#print token
# 	#获得验证码
# 	imageUrl=soup.select('#captchaCode1')[0]['src']
# 	imageHtml=requests.get(imageUrl,headers=infoHead).content
# 	imgFile=StringIO.StringIO(imageHtml) #缓存图片
# 	img=Image.open(imgFile)
# 	vcode = pytesseract.image_to_string(img)
# 	#print (vcode)

# 	# 获取地区id
# 	zone={'北京':'485','天津':'515','河北省':'486','山西省':'487','内蒙古':'488','辽宁省':'489','吉林省':'490','黑龙江省':'491','上海':'492','江苏省':'493','浙江省':'494','安徽省':'495','福建省':'496','江西省':'497','山东省':'498','河南省':'499','湖北省':'500','湖南省':'501','广东省':'502','广西':'503','海南省':'504','重庆':'505','四川省':'506','贵州省':'507','云南省':'508','西藏':'509','陕西省':'510','甘肃省':'511','青海省':'512','宁夏':'513','新疆':'514'}
# 	region_id=zone[addressinfo['region']]
# 	cityData={'region_id':region_id}
# 	cityHtml=requests.post('https://www.adidas.com.cn/specific/ajaxcustomer/ajaxcity',data=cityData,headers=infoHead)
# 	#print cityHtml.text.decode("unicode-escape") #unicode转中文
# 	dic=json.loads(cityHtml.text)
# 	#print dic
# 	city_id=list(dic.keys())[list(dic.values()).index(addressinfo['city'])]
# 	print city_id
	
# 	districtData={'city_id':city_id}
# 	districtHtml=requests.post('https://www.adidas.com.cn/specific/ajaxcustomer/ajaxdistrict',data=districtData,headers=infoHead)
# 	#print districtHtml.text.decode("unicode-escape")
# 	dic=json.loads(districtHtml.text)
# 	#print dic
# 	district_id=list(dic.keys())[list(dic.values()).index(addressinfo['district'])]
# 	print district_id

# 	regData={
# 	 		 'token':token,
# 	         'firstname':addressinfo['firstname'],
# 	         'mobile':registerinfo['mobile'],
# 	         'gender':'1',
# 	         'day':registerinfo['birthday'].split('-')[2],
# 	         'year':registerinfo['birthday'].split('-')[0],
# 	         'dob':registerinfo['birthday'],
# 	         'osolCatchaTxt':vcode,
# 	         'osolCatchaTxtInst':1,
# 	         'email':registerinfo['email'],
# 	         'username':registerinfo['username'],
# 	         'password':registerinfo['password'],
# 	         'confirmation':registerinfo['password'],
# 	         'agree_terms':1}
# 	r=requests.post(regUrl,data=regData,headers =regHead)
# 	cookie=r.cookies
# 	if r.url=='https://www.adidas.com.cn/customer/account/index/isRegister/true/':
# 		print '注册成功',zhuceCode_success

# 		# 注册成功添加收货地址
# 		addresUrl='https://www.adidas.com.cn/customer/address/new/'
# 		addHead={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36',
# 			 'Referer': '',
# 			 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
# 		newaddreshtml=requests.get(addresUrl,headers=infoHead,cookies=cookie)
# 		#print newaddreshtml.text
# 		soup=BeautifulSoup(newaddreshtml.text,'html.parser')
# 		token=soup.select('input')[4]['value']
# 		form_key=soup.select('input')[1]['value']
# 		posturl='https://www.adidas.com.cn/customer/address/formPost/'
# 		userinfo={'form_key':form_key,
# 	        'success_url':'',
# 	        'error_url':'',
# 	        'token':token,
# 	        'country_id':'CN',
# 	        'firstname':addressinfo['firstname'],
# 	        'region_id':region_id, 
# 	        'region':addressinfo['region'],
# 	        'city_id':city_id,
# 	        'district_id':district_id,
# 	        'city':addressinfo['city'],
# 	        'district':addressinfo['district'],
# 	        'street[]':addressinfo['street'],
# 	        'postcode':addressinfo['postcode'],
# 	        'tel_areacode':'',
# 	        'telephone':'',
# 	        'mobile':addressinfo['mobile'],
# 	        'default_billing':'1',
# 	        'default_shipping':'1'}
# 		data=urllib.urlencode(userinfo)
# 		addres=requests.post(posturl,headers=addHead,data=data,cookies=cookie)
# 		return zhuceCode_success
# 	else:
# 		print '注册失败' ,zhuceCode_fail
# 		return zhuceCode_fail
	

	
if __name__ == '__main__':
	# 获取团队id
	t_id=get_tid()
	print t_id
	if t_id:
		while True:
			# 拉任务
			loginHead={'User-Agent':'FLASHSALE',
					   'Referer': 'http://store.nike.com/cn/zh_cn/',
					   'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
					   'X-Requested-With':'XMLHttpRequest'}
			params=urllib.urlencode({'type':1,'tid':t_id})
		 	r=requests.post('http://sale.com/Rpc/planTask',headers=loginHead,data=params)
		 
		 	print r.text.decode('unicode-escape')
		 	if json.loads(r.text)['code'] is 1 and json.loads(r.text)['data'] != []:
		 		tid=json.loads(r.text)['data'][0]['t_id']
			 	stid=json.loads(r.text)['data'][0]['site_id']
			 	#print t_id,site_id
			 	params=urllib.urlencode({'tid':tid,'stid':stid})
			 	r=requests.post('http://sale.com/Rpc/redisteruser',headers=loginHead,data=params)
			 	print r.text
			 	if json.loads(r.text)['code'] is 4001:
			 		print "无数据"
			 		break
			 	elif json.loads(r.text)['code'] is 1:
			 		print r.text.decode('unicode-escape')
					# 网站标识
					website=json.loads(json.loads(r.text)['data']['site_id'])


					# 注册完成状态码
					zhuceCode_success='2'
					zhuceCode_fail='1'

					#print type(json.loads(r.text)['data']['u_field']['addressremark']['province'])
					# 动态信息
					data=json.loads(r.text)['data']
					addressremark=data['u_field']['addressremark']
					registerinfo={'email':data['u_eamil'],
								  'mobile':data['mobile'],
								  'username':data['u_name'],
								  'password':data['u_pwd'],
								  'birthday':data['birthday']
								  }
					addressinfo={ 'firstname':data['firstname'].encode('utf8'),
					              'region':addressremark['province'].encode('utf8'),
							      'city':addressremark['city'].encode('utf8'),
							      'district':addressremark['district'].encode('utf8'),
							      'street':(addressremark['street']+data['u_address']).encode('utf8'),
							      'delivery_memo':data['u_address'].encode('utf8'),
							      'postcode':data['u_addresscode'].encode('utf8'),
							      'mobile':data['mobile'].encode('utf8')
							      }

					# 平台选择
					if website is 3:
						if nike(registerinfo,addressinfo)=='2':
							params=urllib.urlencode({'tid':tid,'stid':stid,'uid':data['u_id'],'type':'2'})  #type 1注册失败，2注册成功
				 			r=requests.post('http://sale.com/Rpc/registerRollback',headers=loginHead,data=params)
				 		else:
				 				params=urllib.urlencode({'tid':tid,'stid':stid,'uid':data['u_id'],'type':'1'})
				 				r=requests.post('http://sale.com/Rpc/registerRollback',headers=loginHead,data=params)


					if website is 1:
						if adidas(registerinfo,addressinfo)=='2': #1注册失败，2注册成功
								params=urllib.urlencode({'tid':tid,'stid':stid,'uid':data['u_id'],'type':'2'})
				 				r=requests.post('http://sale.com/Rpc/registerRollback',headers=loginHead,data=params)
				 		else:
				 				params=urllib.urlencode({'tid':tid,'stid':stid,'uid':data['u_id'],'type':'1'})
				 				r=requests.post('http://sale.com/Rpc/registerRollback',headers=loginHead,data=params)
				
			else:
				print '无数据'
				break



